<template>
  <div class="wrapper">
    <h1>我的设备</h1>
    <!-- 搜索设备 -->
    <div class="container addDevices" @click="searchDevice" v-if="!devices.name">
      <img src="../../../static/controller/add.png" alt="add_devices" />
      <span>搜索设备</span>
    </div>
    <!-- 连接设备  -->
    <div class="container connectDevices" v-if="isSearchDev">
      <div class="deviceName">
        <h2>设备名称</h2>
        <span>MINI-001</span>
        <span>BEOKA-MINI颈椎按摩仪</span>
      </div>
      <div class="deviceBlue">
        <img src="../../../static/controller/blurtoothIco.png" alt="蓝牙ico" />
        <span>{{isConnect?'已连接':'已断开'}}</span>
        <button
          @click="createBLEConnection"
          hover-stay-time="150"
          hover-class="shaow"
          plain="true"
          size="mini"
          v-if="!isConnect"
        >连接</button>
        <button hover-stay-time="150" hover-class="shaow" plain="true" size="mini">断开</button>
      </div>
      <img src="../../../static/controller/miniProdouctImg.png" />
    </div>
    <!-- 控制器   -->
    <div class="controller" v-if="isConnect">
      <!-- 减 -->
      <img class="reduce" src="../../../static/controller/reduce.png" alt="减" @click="reduce" />
      <!-- 产品名字 -->
      <div class="mini-name">
        <p>BEOKA-MINI颈椎按摩仪</p>
        <span>MINI-001</span>
      </div>
      <!-- 模式选择 -->
      <div class="mini-mode">
        <img
          v-for="(item,index) in modeIMG"
          :key="index"
          :src="item"
          @click="toggleMode(index)"
          alt
        />
      </div>
      <!-- 大小控制器 -->
      <div class="mini-controler">
        <!-- 圈 -->
        <div class="controllerCicle"></div>
        <div class="controllerNumber"></div>
        <!-- 加 -->
        <img @click="add" class="add" src="../../../static/controller/add1.png" alt="加" />
        <!-- 当前数值 -->
        <span class="leavel" :class="leavel>9?'postion':''">{{leavel}}</span>
        <b>当前强度</b>
      </div>
      <!-- 加热 和 语音 -->
      <div class="heatAndVoice">
        <div>
          <span>加热</span>
          <i-switch :value="heat" @tap="toggleHeat"></i-switch>
        </div>
        <div>
          <span>语音</span>
          <i-switch :value="voice" @tap="toggleVoice"></i-switch>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import modeIMG0 from "../../../static/controller/1.png";
import modeIMG1 from "../../../static/controller/3.png";
import modeIMG2 from "../../../static/controller/5.png";
import modeACtive0 from "../../../static/controller/2.png";
import modeACtive1 from "../../../static/controller/4.png";
import modeACtive2 from "../../../static/controller/6.png";
import { ab2hex, arr2ab } from "../../blueToothAPI/index.js";
export default {
  data() {
    return {
      isSearchDev: false,
      isConnect: false,
      heat: false,
      voice: true,
      modeIMG: [
        "../../static/controller/1.png",
        "../../static/controller/4.png",
        "../../static/controller/5.png"
      ],
      mode1: false,
      mode2: true,
      mode3: false,
      leavel: 0,
      devices: {},
      services: [],
      Char: [],
      openHeat: [58, 58, 1, 1, 2, 2, 22, 1, 33, 33],
      closeHeat: [58, 58, 1, 1, 2, 2, 22, 2, 33, 33],
      colseVoice: [58, 58, 1, 1, 2, 2, 21, 2, 33, 33],
      openVoice: [58, 58, 1, 1, 2, 2, 21, 1, 33, 33],
      openMode1: [58, 58, 1, 1, 2, 2, 2, 5, 33, 33],
      closeMode1: [58, 58, 1, 1, 2, 3, 2, 5, 2, 33, 33],
      openMode2: [58, 58, 1, 1, 2, 2, 2, 7, 33, 33],
      closeMode2: [58, 58, 1, 1, 2, 3, 2, 7, 2, 33, 33],
      openMode3: [58, 58, 1, 1, 2, 2, 2, 8, 33, 33],
      closeMode3: [58, 58, 1, 1, 2, 3, 2, 8, 2, 33, 33],
      leavelAdd: [58, 58, 1, 1, 1, 2, 4, 1, 33, 33],
      leavelReduce: [58, 58, 1, 1, 1, 2, 4, 2, 33, 33]
    };
  },
  beforeMount() {},
  methods: {
    // 强度减
    reduce() {
      let leavelReduceValue = arr2ab(this.leavelReduce);
      wx.writeBLECharacteristicValue({
        deviceId: this.devices.deviceId,
        serviceId: this.services.uuid,
        characteristicId: this.Char[0].uuid,
        value: leavelReduceValue,
        success: res => {
          console.log("写入 强度减 成功！", res);
        },
        fail: res => {
          console.log("写入 强度减 失败！", res);
        }
      });
    },
    // 强度加
    add() {
      let leavelAddValue = arr2ab(this.leavelAdd);
      wx.writeBLECharacteristicValue({
        deviceId: this.devices.deviceId,
        serviceId: this.services.uuid,
        characteristicId: this.Char[0].uuid,
        value: leavelAddValue,
        success: res => {
          console.log("写入 强度加 成功！", res);
        },
        fail: res => {
          console.log("写入 强度加 失败！", res);
        }
      });
    },
    //切换模式
    toggleMode(index) {
      if (index === 0) {
        if (!this.mode1) {
          // 蓝牙通信，修改为自身mode为true
          let openMode1Value = arr2ab(this.openMode1);
          wx.writeBLECharacteristicValue({
            deviceId: this.devices.deviceId,
            serviceId: this.services.uuid,
            characteristicId: this.Char[0].uuid,
            value: openMode1Value,
            success: res => {
              console.log("写入 打开mode1 成功！", res);
            },
            fail: res => {
              console.log("写入 打开mode1 失败！", res);
            }
          });
        }
        return;
      } else if (index === 1) {
        if (!this.mode2) {
          // 蓝牙通信，修改为自身mode为true
          let openMode2Value = arr2ab(this.openMode2);
          wx.writeBLECharacteristicValue({
            deviceId: this.devices.deviceId,
            serviceId: this.services.uuid,
            characteristicId: this.Char[0].uuid,
            value: openMode2Value,
            success: res => {
              console.log("写入 打开mode2 成功！", res);
            },
            fail: res => {
              console.log("写入 打开mode2 失败！", res);
            }
          });
        }
        return;
      } else {
        if (!this.mode3) {
          // 蓝牙通信，修改为自身mode为true
          let openMode3Value = arr2ab(this.openMode3);
          wx.writeBLECharacteristicValue({
            deviceId: this.devices.deviceId,
            serviceId: this.services.uuid,
            characteristicId: this.Char[0].uuid,
            value: openMode3Value,
            success: res => {
              console.log("写入 打开mode3 成功！", res);
            },
            fail: res => {
              console.log("写入 打开mode3 失败！", res);
            }
          });
        }
        return;
      }
    },
    // 搜索设备
    searchDevice() {
      wx.openBluetoothAdapter({
        success: res => {
          console.log("初始化蓝牙模块成功！", res);
          wx.showToast({
            icon: "loading",
            title: "正在搜索...",
            duration: 2500
          });
          this._startBluetoothDevicesDiscovery();
        },
        fail: res => {
          console.log("初始化蓝牙模块失败！", res);
          if (res.errCode === 10001) {
            wx.showToast({
              icon: "loading",
              title: "请打开手机蓝牙",
              duration: 1000
            });
            wx.onBluetoothAdapterStateChange(res => {
              if (res.available) {
                this._startBluetoothDevicesDiscovery();
              }
            });
          }
        }
      });
    },
    _startBluetoothDevicesDiscovery() {
      wx.startBluetoothDevicesDiscovery({
        success: res => {
          console.log("正在搜索周围设备：", res);
          wx.onBluetoothDeviceFound(res => {
            console.log("监听到周围设备：", res);
            if (res.devices[0].name == "JDY-08") {
              this.devices = res.devices[0];
              console.log("倍益康MINI颈椎设备添加成功：", this.devices);
              this.isSearchDev = true;
              return;
            }
          });
        },
        fail: res => {
          console.log("搜索失败：", res);
        }
      });
    },
    // 连接设备
    createBLEConnection() {
      wx.createBLEConnection({
        deviceId: this.devices.deviceId,
        success: res => {
          console.log("连接成功", res);
          wx.stopBluetoothDevicesDiscovery({
            success: res => {
              console.log("已成功连接，自动停止搜索。释放资源");
              this.isConnect = true;
              this.isSearchDev = false;
              wx.showToast({
                title: "连接成功",
                icon: "success",
                duration: 2000
              });
            }
          });
          this._getBLEDeviceServices();
        },
        fail: res => {
          console("连接设备失败", res);
        }
      });
    },
    //获取服务并开启特征值通知和回调
    _getBLEDeviceServices() {
      wx.getBLEDeviceServices({
        deviceId: this.devices.deviceId,
        success: res => {
          console.log("获取倍益康MINI颈椎设备的服务如下：");
          console.log("服务总个数为：", res.services.length);
          console.log(res);
          this.services = res.services[0];
          wx.getBLEDeviceCharacteristics({
            deviceId: this.devices.deviceId,
            serviceId: this.services.uuid,
            success: res => {
              console.log("服务特征值如下：");
              console.log("共" + res.characteristics.length + "向特征值");
              console.log(res);
              this.Char.push(res.characteristics[0]);
              wx.notifyBLECharacteristicValueChange({
                state: true,
                deviceId: this.devices.deviceId,
                serviceId: this.services.uuid,
                characteristicId: this.Char[0].uuid,
                success: res => {
                  console.log("开启notif成功！", res);
                  wx.onBLECharacteristicValueChange(res => {
                    var backArr = ab2hex(res.value);
                    var leng = backArr.length;
                    if (
                      backArr[0] == "3a" &&
                      backArr[1] == "3a" &&
                      backArr[leng - 1] == "21" &&
                      backArr[leng - 2] == "21"
                    ) {
                      // 接触不良
                      if (backArr[3] === "05" && backArr[6] === "04") {
                        console.log("接触不良");
                        this.leavel = 0;
                      } else if (
                        backArr[leng - 4] === "16" &&
                        backArr[leng - 3] === "01"
                      ) {
                        this.heat = true;
                        console.log("打开加热成功！", this.heat);
                      } else if (backArr[6] === "16" && backArr[7] === "02") {
                        this.heat = false;
                        console.log("关闭加热成功！", this.heat);
                      } else if (backArr[6] === "15" && backArr[7] === "01") {
                        this.voice = true;
                        console.log("打开语音成功！", this.voice);
                      } else if (backArr[6] === "15" && backArr[7] === "02") {
                        this.voice = false;
                        console.log("关闭语音成功！", this.voice);
                      } else if (
                        backArr[leng - 4] === "02" &&
                        backArr[leng - 3] === "05"
                      ) {
                        this.mode1 = true;
                        this.mode2 = false;
                        this.modeIMG[1] = modeIMG1;
                        this.mode3 = false;
                        this.modeIMG[2] = modeIMG2;
                        this.modeIMG[0] = modeACtive0;
                        console.log("打开 mode1 成功！", this.mode1);
                      } else if (
                        backArr[leng - 4] === "02" &&
                        backArr[leng - 3] === "07"
                      ) {
                        this.mode2 = true;
                        this.mode1 = false;
                        this.modeIMG[0] = modeIMG0;
                        this.mode3 = false;
                        this.modeIMG[2] = modeIMG2;
                        this.modeIMG[1] = modeACtive1;
                        console.log("打开 mode2 成功！", this.mode2);
                      } else if (
                        backArr[leng - 4] === "02" &&
                        backArr[leng - 3] === "08"
                      ) {
                        this.mode3 = true;
                        this.mode1 = false;
                        this.modeIMG[0] = modeIMG0;
                        this.mode2 = false;
                        this.modeIMG[1] = modeIMG1;
                        this.modeIMG[2] = modeACtive2;
                        console.log("打开 mode3 成功！", this.mode3);
                      } else if (
                        backArr[leng - 4] === "04" &&
                        backArr[leng - 3] === "01"
                      ) {
                        if (this.leavel < 20) {
                          this.leavel++;
                          console.log(" 强度增加 成功！", this.leavel);
                        } else {
                          console.log("设备强度值已到最高:", this.leavel);
                        }
                      } else if (
                        backArr[leng - 4] === "04" &&
                        backArr[leng - 3] === "02" &&
                        backArr[4] === "01"
                      ) {
                        if (this.leavel > 0) {
                          this.leavel--;
                          console.log(" 强度增加 成功！", this.leavel);
                        } else {
                          console.log("设备强度值已到最低:", this.leavel);
                        }
                      }
                    }
                    console.log("接收到的数据为", ab2hex(res.value));
                  });
                }
              });
            }
          });
        }
      });
    },
    //加热开关
    toggleHeat() {
      //打开加热
      if (!this.heat) {
        let openHeatValue = arr2ab(this.openHeat);
        wx.writeBLECharacteristicValue({
          deviceId: this.devices.deviceId,
          serviceId: this.services.uuid,
          characteristicId: this.Char[0].uuid,
          value: openHeatValue,
          success: res => {
            console.log("写入打开加热成功！", res);
          },
          fail: res => {
            console.log("写入打开加热失败！", res);
          }
        });
      } else {
        let closeHeatValue = arr2ab(this.closeHeat);
        wx.writeBLECharacteristicValue({
          deviceId: this.devices.deviceId,
          serviceId: this.services.uuid,
          characteristicId: this.Char[0].uuid,
          value: closeHeatValue,
          success: res => {
            console.log("写入关闭加热成功！", res);
          },
          fail: res => {
            console.log("写入关闭加热失败！", res);
          }
        });
      }
    },
    //语音开关
    toggleVoice() {
      //语音关
      if (this.voice) {
        let colseVoiceValue = arr2ab(this.colseVoice);
        wx.writeBLECharacteristicValue({
          deviceId: this.devices.deviceId,
          serviceId: this.services.uuid,
          characteristicId: this.Char[0].uuid,
          value: colseVoiceValue,
          success: res => {
            console.log("写入关闭语音成功！", res);
          },
          fail: res => {
            console.log("写入关闭语音失败！", res);
          }
        });
      } else {
        let openVoiceValue = arr2ab(this.openVoice);
        wx.writeBLECharacteristicValue({
          deviceId: this.devices.deviceId,
          serviceId: this.services.uuid,
          characteristicId: this.Char[0].uuid,
          value: openVoiceValue,
          success: res => {
            console.log("写入 打开语音 成功！", res);
          },
          fail: res => {
            console.log("写入 关闭语音 失败！", res);
          }
        });
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #ffffff;
}
h1 {
  width: 90%;
  font-size: 35rpx;
  margin-top: 50rpx;
}
/* 公共类 */
.container {
  width: 90%;
  height: 363rpx;
  background-color: #eeeeee;
  margin: 20rpx 0 25rpx 0;
  border-radius: 20rpx;
  box-shadow: 10rpx 10rpx 10rpx #e9e9e9;
}
/* 搜索设备 */
.addDevices {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #afafaf;
  img {
    width: 80rpx;
    height: 80rpx;
    margin-bottom: 5rpx;
  }
}
/* 连接设备 */
.connectDevices {
  display: flex;
  flex-flow: column;
  justify-content: space-between;
  position: relative;
  background-color: #306cff;
  color: #ffffff;
  padding-left: 30rpx;

  .deviceName {
    display: flex;
    flex-flow: column;
    margin-top: 20rpx;
    h2 {
      margin-bottom: 50rpx;
    }
  }
  .deviceBlue {
    display: flex;
    align-items: center;
    margin-bottom: 30rpx;
    img {
      width: 55rpx;
      height: 55rpx;
    }
    button {
      color: #ffffff;
      border-color: #ffffff;
    }
  }
  > img {
    position: absolute;
    width: 300rpx;
    height: 300rpx;
    right: 30rpx;
    top: -66rpx;
  }
}
.shaow {
  background-color: rgb(124, 120, 120);
}
/* 控制器 */
.controller {
  width: 90%;
  position: relative;
  > img {
    position: absolute;
    top: 57%;
    width: 70rpx;
    height: 70rpx;
    z-index: 999;
  }
  .mini-name {
    display: flex;
    flex-direction: column;
    align-items: center;
    color: #5f5f5f;
    font-size: 30rpx;
    margin: 80rpx;
  }
  .mini-mode {
    display: flex;
    justify-content: space-around;
    width: 100%;
    margin: 50rpx 0;
    img {
      width: 130rpx;
      height: 150rpx;
    }
  }
  .mini-controler {
    width: 100%;
    height: 345rpx;
    position: relative;
    img {
      width: 75rpx;
      height: 75rpx;
    }
    .reduce {
      position: absolute;
      top: 50%;
      left: 0;
    }
    .controllerCicle {
      width: 100%;
      height: 100%;
      // background-image: url("");
      background-size: cover;
    }
    .controllerNumber {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-image: url("");
      background-size: cover;
    }
    .add {
      position: absolute;
      top: 50%;
      right: 0;
    }
    .leavel {
      position: absolute;
      top: 50%;
      left: 50%;
      margin-left: -50rpx;
      margin-top: -50px;
      font-size: 180rpx;
      color: #2c68fe;
    }
    .postion {
      margin-left: -100rpx;
    }
    b {
      position: absolute;
      bottom: -20rpx;
      left: 50%;
      margin-left: -60rpx;
      color: #5f5f5f;
      font-size: 35rpx;
    }
  }
  .heatAndVoice {
    display: flex;
    justify-content: center;
    margin: 130rpx 0 120rpx 0;
    color: #979797;
    width: 100%;
    div {
      width: 50%;
      display: flex;
      justify-content: center;
      span {
        margin-right: 10rpx;
      }
    }
  }
}
</style>

